import {
	defineStore
} from 'pinia';
import api from '@/api/home.js';
import prefix from '@/utils/prefix.js';

export const useHomeStore = defineStore('home', {
	state: () => ({
		selectedImages: [],
		uploading: false,
		uploadPercent: 0,
		previewImages: [],
		isUploaded: [],
		horizontal: 'left',
		typeList: [],
		fabStyle: {
			horizontal: 'right',
			vertical: 'bottom',
			direction: 'horizontal',
		},
		vmenu: [{
				iconPath: '/static/img/pz_active.png',
				selectedIconPath: '/static/img/pz_active.png',
				text: '上传照片',
				active: false,
			},
			{
				iconPath: '/static/img/fenlei_active.png',
				selectedIconPath: '/static/img/fenlei_active.png',
				text: '新增分类',
				active: false,
			},
		],
	}),
	actions: {
		async initTypelist() {
			const res = await api.getTypeList({
				page: 0,
				limit: 9999
			});
			if (res.data != null) {
				debugger
				this.typeList = res.data.reduce((pre, cur) => {
					pre.push(cur.id + '-' + cur.typeName);
					return pre;
				}, []);
			}
		},
		openMedia() {
			uni.chooseImage({
				count: 6,
				sourceType: ['camera', 'album'],
				success: (res) => {
					this.selectedImages = res.tempFilePaths;
					this.previewImages = new Array(res.tempFilePaths.length).fill(false);
					this.isUploaded = new Array(res.tempFilePaths.length).fill(false);
					// 添加过渡动画类名
					document.querySelectorAll('.image-grid view').forEach((item, index) => {
						item.classList.add('fade-in');
						setTimeout(() => {
							item.classList.remove('fade-in');
						}, 500);
					});
				},
			});
		},
		async uploadImages() {
			let selectType;
			uni.showActionSheet({
				itemList: [...this.typeList],
				success: function(res) {
					selectType = this.typeList[res.tapIndex];
					this.uploading = true;
					try {
						var token = uni.getStorageSync('Authorization');
					} catch (e) {}

					const imageUploadPromises = this.selectedImages.map((filePath, index) => {
						return new Promise((resolve, reject) => {
							uni.uploadFile({
								url: prefix + 'Picture/UploadImage',
								filePath,
								name: 'file',
								header: {
									Authorization: token,
								},
								formData: {
									userName: uni.getStorageSync(
										'userName'),
									typeName: selectType,
								},
								success: (res) => {
									if (res.statusCode == 200) {
										this.isUploaded[index] =true;
										resolve(res);
									} else {
										this.isUploaded[index] =false;
										reject(res);
									}
								},
								fail: (err) => {
									uni.showModal({
										title: '提示',
										content: '上传失败',
										showCancel: false,
									});
									this.isUploaded[index] = false;
									reject(err);
								},
								onProgressUpdate: (res) => {
									if (index == this
										.selectedImages.length - 1
										) {
										this.uploadPercent = res
											.progress;
									}
								},
							});
						});
					});
					Promise.all(imageUploadPromises)
						.then(() => {
							uni.showToast({
								title: '上传完成',
								icon: 'success',
							});
							setTimeout(() => {
								this.selectedImages = [];
							}, 1000);
						})
						.catch((e) => {
							console.log(e);
							uni.showToast({
								title: '部分上传失败',
								icon: 'error',
							});
						})
						.finally(() => {
							this.uploading = false;
						});
				},
				fail: function(res) {
					console.log(res.errMsg);
				},
			});
		},
		toggleImagePreview(index) {
			this.previewImages[index] = !this.previewImages[index];
			if (this.previewImages[index]) {
				uni.previewImage({
					urls: this.selectedImages,
					current: index,
				});
			}
		},
		removeImage(index) {
			this.selectedImages.splice(index, 1);
			this.previewImages.splice(index, 1);
			this.isUploaded.splice(index, 1);
		},
		getIcon(index) {
			if (this.isUploaded[index]) {
				return 'checkmarkempty';
			} else {
				return 'closeempty';
			}
		},
		getColor(index) {
			if (this.isUploaded[index]) {
				return '#00ff00';
			} else {
				return '#ff0000';
			}
		},
		trigger(index) {
			if (index == 0) {
				this.openMedia();
			} else if (index == 1) {
				uni.showModal({
					title: '分类名称',
					placeholderText: '输入分类名称...',
					editable: true,
					success: (res) => {
						if (res.confirm) {
							console.log(res.content);
							api.modifyType({
								typeName: res.content
							}).then((res) => {
								uni.showToast({
									title: res.msg,
									duration: 500,
									icon: 'success',
								});
							}).catch((err) => {
								debugger;
								console.log(err);
							});
						}
						setTimeout(() => this.initTypelist(), 500);
					},
				});
			} else {
				// 其他情况
			}
		},
	},
});